package com.tanhua.server.controller;

import com.tanhua.dubbo.server.vo.CommentType;
import com.tanhua.dubbo.server.vo.IdType;
import com.tanhua.server.service.QuanZiService;
import com.tanhua.server.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("comments")
public class CommentController {
    @Autowired
    QuanZiService quanZiService;


    /**
     * 控制层实现功能:点赞评论
     */
    @GetMapping("/{id}/like")
    public Long evaluationLikeComment(@PathVariable("id") String publishId) {
        Long count = null;
        try {
            count = quanZiService.likeAndLove(publishId, CommentType.LIKE, IdType.COMMENT);
            if (count == null) {
                log.error("点赞失败!");
                return null;
            }
        } catch (Exception e) {
            log.error("点赞异常!");
            return null;
        }
        return count;
    }

    /**
     * 控制层实现功能:取消点赞评论
     */
    @GetMapping("/{id}/dislike")
    public Long evaluationCancelLikeComment(@PathVariable("id") String publishId) {
        Long count = null;
        try {
            count = quanZiService.likeCancelAndLove(publishId, CommentType.LIKE, IdType.PUBLISH);
            if (count == null) {
                log.error("点赞失败!");
                return null;
            }
        } catch (Exception e) {
            log.error("点赞异常!");
            return null;
        }
        return count;
    }


    /**
     * 保存评论
     */
    @PostMapping
    public ResponseEntity<Void> saveCommentPublish(@RequestBody Map<String, String> param) {
        Boolean result = null;
        try {
            String movementId = param.get("movementId");
            String comment = param.get("comment");
            result = quanZiService.saveCommentPublish(movementId, comment);
            if (!result) {
                return ResponseEntity.status(500).build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok(null);
    }


    /**
     * 评论列表
     */
    @GetMapping
    public ResponseEntity<PageResult> findAllComment(
            @RequestParam("movementId") String publishId,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pagesize", defaultValue = "10") Integer pageSize) {
        PageResult pageResult = null;
        try {
            pageResult = quanZiService.findAllComment(publishId, page, pageSize);
            if (pageResult == null) {
                return ResponseEntity.status(500).build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(501).build();
        }
        return ResponseEntity.ok(pageResult);
    }

}
